package com.attendance.utils;


import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class GenerateVerificationCode {

    public final static String NUMBER = "NUMBER";

    public final static String LETTER_UP = "LETTER_UP";

    public final static String LETTER_DOWN = "LETTER_DOWN";

    public final static String ALL = "ALL";

    private final static String number = "1234567890";

    private final static String letter_up = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private final static String letter_down = "abcdefghijklmnopqrstuvwxyz";

    private final static PasswordEncoder encoder = new BCryptPasswordEncoder();

    private final static Random r = new Random();

    public String build(String type, int length) {
        StringBuilder result = new StringBuilder();
        switch (type) {
            case NUMBER -> {
                for (int i = 0; i < number.length(); i++) {
                    result.append(number.charAt(r.nextInt(number.length())));
                }
            }
            case LETTER_UP -> {
                for (int i = 0; i < letter_up.length(); i++) {
                    result.append(letter_up.charAt(r.nextInt(letter_up.length())));
                }
            }
            case LETTER_DOWN -> {
                for (int i = 0; i < letter_down.length(); i++) {
                    result.append(letter_down.charAt(r.nextInt(letter_down.length())));
                }
            }
            case ALL -> {
                String all = letter_down + letter_up + number;
                for (int i = 0; i < all.length(); i++) {
                    result.append(all.charAt(r.nextInt(all.length())));
                }
            }
        }
        if (!(length > result.length())) {
            result.setLength(length);
        }
        return result.toString();
    }

    public String encode(String code) {
        return encoder.encode(code);
    }

    public Boolean verifyCode(String code, String encode, long time) {
        // 十五分钟有效期
        if ((System.currentTimeMillis() - time) > 900000) {
            return false;
        }
        return encoder.matches(code, encode);
    }

}
